package com.czl.module_storehouse.activity.allocate.add;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.core.content.ContextCompat;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.bean.CompanyBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_service.event.AllocateAddEvent;
import com.czl.module_service.event.StorehouseHomeScanBackEvent;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.adapter.AllocateAddAdapter;
import com.czl.module_storehouse.bean.AddMoveInfoBean;
import com.czl.module_storehouse.bean.StoreHouseBean;
import com.czl.module_storehouse.bean.WorkGroupBean;
import com.czl.module_storehouse.bean.WorkerBean;
import com.czl.module_storehouse.databinding.ActivityBaseOperationBinding;
import com.czl.module_storehouse.databinding.HeaderAllocateAddBinding;
import com.czl.module_storehouse.listener.OnItemChangeListener;
import com.czl.module_storehouse.mvp.presenter.AllocatePresenter;
import com.czl.module_storehouse.mvp.presenter.CompanyPresenter;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.presenter.StorehousePresenter;
import com.czl.module_storehouse.mvp.view.AllocateView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 添加调拨单
 *
 * @author xubin
 */
public class AllocateAddActivity extends BaseOperationActivity<ActivityBaseOperationBinding> implements OnItemChangeListener,
        SimpleView, AllocateView {

    private final AddMoveInfoBean mAddMoveInfoBean = new AddMoveInfoBean();
    private List<CompanyBean> mCompanyBeanList;
    private String mPreCompanyId;
    private AllocateAddAdapter mAdapter;
    @InjectPresenter
    AllocatePresenter mAllocatePresenter;
    @InjectPresenter
    CompanyPresenter mCompanyPresenter;
    @InjectPresenter
    StorehousePresenter mStorehousePresenter;
    @InjectPresenter
    ProductPresenter mProductPresenter;
    private HeaderAllocateAddBinding mHeaderBinding;
    private List<StoreHouseBean> mStoreHouseBeanList;

    @Override
    protected ProductPresenter getProductPresenter() {
        return mProductPresenter;
    }

    @Override
    protected ActivityBaseOperationBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseOperationBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("调拨单");
        binding.btnSure.setText("调拨出库");
        binding.recyclerView.setAdapter(getAdapter());
        mCommonSelectedOrScanBinding.textScan.setText("扫码调拨物品");
        mCommonSelectedOrScanBinding.textSelected.setText("选择调拨物品");
        mCommonSelectedOrganizationBinding.stvOrganization.setLeftString("申调部门：");
        mCommonSelectedOrganizationBinding.stvOrganization.setRightTextColor(ContextCompat.getColor(getContext(), R.color.color_999999));
        mCommonSelectedOrganizationBinding.stvPersonnel.setLeftString("申请人：");
        mCommonSelectedOrganizationBinding.stvPersonnel.setRightTextColor(ContextCompat.getColor(getContext(), R.color.color_999999));
        mCommonSelectedOrganizationBinding.stvOrganization.setRightString("选择部门");
        mCommonSelectedOrganizationBinding.stvPersonnel.setRightString("选择申请人");
    }

    @Override
    protected String getOperationTitle() {
        return "调拨";
    }

    @Override
    protected ViewGroup selectedOrganizationView() {
        return mHeaderBinding.flContent;
    }

    @Override
    protected ViewGroup selectedScanContainerView() {
        return mHeaderBinding.flAdd;
    }

    @Override
    protected void selectOrganization() {
        super.selectOrganization();
        String applyCompanyId = mAddMoveInfoBean.getApplyCompanyId();
        if (TextUtils.isEmpty(applyCompanyId)) {
            showToast("请先选择申请公司");
            return;
        }
        mCompanyPresenter.selectOrganization(applyCompanyId);
    }

    @Override
    protected void selectUsersByCompanyId() {
        super.selectUsersByCompanyId();
        String applyCompanyId = mAddMoveInfoBean.getApplyCompanyId();
        mCompanyPresenter.selectUsersByCompanyId(applyCompanyId, mOrganizationId);
    }

    private void selectCompanyList() {
        if (mCompanyBeanList == null) {
            mCompanyPresenter.selectCompanyList();
        } else {
            showCompanyPopup();
        }
    }

    private void showCompanyPopup() {
        List<String> list = new ArrayList<>();
        if (mCompanyBeanList != null) {
            for (CompanyBean bean : mCompanyBeanList) {
                String companyName = bean.getCompanyName();
                if (TextUtils.isEmpty(companyName)) {
                    continue;
                }
                list.add(companyName);
            }
        }
        showRecyclerViewPopupWindow(list, "选择公司", (adapter, view, position) -> {
            CompanyBean bean = mCompanyBeanList.get(position);
            String companyId = bean.getCompanyId();
            if (!TextUtils.isEmpty(mPreCompanyId) && !mPreCompanyId.equals(companyId)) {
                mWorkGroupBeanList = null;
                mCommonSelectedOrganizationBinding.stvOrganization.setRightString("选择部门");
                mCommonSelectedOrganizationBinding.stvPersonnel.setRightString("选择申请人");
                mHeaderBinding.tvInHouse.setText("选择仓库");
                mAddMoveInfoBean.setInStorehouseId(0);
            }
            mAddMoveInfoBean.setApplyCompanyId(bean.getCompanyId());
            mAddMoveInfoBean.setApplyCompanyName(bean.getCompanyName());
            mAddMoveInfoBean.setApplyCompanyShortName(bean.getCompanyShortName());
            mPreCompanyId = companyId;
            mHeaderBinding.tvCompany.setText(bean.getCompanyName());
        });
    }

    @Override
    protected void submit() {
        if (TextUtils.isEmpty(mOrganizationId)) {
            if (mWorkerBean == null) {
                showToast("请选择申调部门");
                return;
            }
        }
        if (mWorkerBean == null) {
            showToast("请选择申请人");
            return;
        }
        mAddMoveInfoBean.setApplyPersonId(mWorkerBean.getUserId());
        mAddMoveInfoBean.setApplyPersonName(mWorkerBean.getTname());

        //移出仓库
//        int moveStorehouseId = mAddMoveInfoBean.getMoveStorehouseId();
//        if (moveStorehouseId == 0) {
//            showToast("请选择调出仓库");
//            return;
//        }
        int inStorehouseId = mAddMoveInfoBean.getInStorehouseId();
        if (inStorehouseId == 0) {
            showToast("请选择调入仓库");
            return;
        }
        List<SortBean> list = new ArrayList<>();
        List<ProductBean> productList = new ArrayList<>();
        for (SortBean sortBean : mAdapter.getData()) {
            if (sortBean.getProductBean() == null) {
                list.add(sortBean);
            } else {
                productList.add(sortBean.getProductBean());
            }
        }
        mAddMoveInfoBean.setSortList(list);
        mAddMoveInfoBean.setProductList(productList);
        mAddMoveInfoBean.setMoveComment(mFooterBinding.etRemark.getText().toString());
        String desc = mHeaderBinding.etReason.getText().toString();
        mAddMoveInfoBean.setApplyComment(desc);
        if (mAllocatePresenter != null) {
            mAllocatePresenter.addMoveInfo(mAddMoveInfoBean);
        }
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new AllocateAddAdapter(new ArrayList<>(), this);
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> startActivity(position));
            mHeaderBinding = HeaderAllocateAddBinding.inflate(getLayoutInflater());
            mAdapter.addHeaderView(mHeaderBinding.getRoot());
            mHeaderBinding.tvInHouse.setOnClickListener(v -> getManageCompanystorehouseList());
            mHeaderBinding.tvCompany.setOnClickListener(v -> selectCompanyList());
            addFooterView(mAdapter);
        }
        return mAdapter;
    }

    @Override
    protected Button getButton() {
        return binding.btnSure;
    }

    @Override
    protected int getMaxNum(SortBean sortBean) {
        return Integer.MAX_VALUE;
    }

    private void getManageCompanystorehouseList() {
        String applyCompanyId = mAddMoveInfoBean.getApplyCompanyId();
        if (TextUtils.isEmpty(applyCompanyId)) {
            showToast("请先选择申请公司");
            return;
        }
        mStorehousePresenter.getStorehouseByUserId();
    }

    @Override
    public void onChange(int position) {
        setReceiveOrBorrowEnable();
    }

    @Override
    public void add(int position) {
        setReceiveOrBorrowEnable();
    }

    @Override
    public void remove(int position) {
        setReceiveOrBorrowEnable();
    }

    private void showPopup() {
        if (mStoreHouseBeanList.size() == 0) {
            showToast("没有仓库，请创建仓库!");
            return;
        }
        int storehouseId = SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID);
        List<StoreHouseBean> newList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (StoreHouseBean bean : mStoreHouseBeanList) {
            if (storehouseId != bean.getStorehouseId()) {
                newList.add(bean);
                list.add(bean.getStorehouseName());
            }
        }

        showRecyclerViewPopupWindow(list, "选择仓库", (adapter, view, position) -> {
            StoreHouseBean storeHouseBean = newList.get(position);
            mAddMoveInfoBean.setInStorehouseId(storeHouseBean.getStorehouseId());
            mHeaderBinding.tvInHouse.setText(storeHouseBean.getStorehouseName());
        });
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (CompanyPresenter.TAG_COMPANY_GROUP.equals(httpResponse.getRequestTag())) {
            addChildWorkGroup(((ListBean<WorkGroupBean>) httpResponse.getData()).getList());
            showPopupWindowGroup();
        } else if (CompanyPresenter.TAG_COMPANY_USER_LIST.equals(httpResponse.getRequestTag())) {
            mWorkerBeanList = ((ListBean<WorkerBean>) httpResponse.getData()).getList();
            showPopupWindowUsers();
        } else if (CompanyPresenter.TAG_COMPANY_LIST.equals(httpResponse.getRequestTag())) {
            mCompanyBeanList = (List<CompanyBean>) httpResponse.getData();
            showCompanyPopup();
        } else if (StorehousePresenter.TAG_STOREHOUSE_LIST.equals(httpResponse.getRequestTag())) {
            Object data = httpResponse.getData();
            List<StoreHouseBean> storeHouseBeans = ((ListBean<StoreHouseBean>) data).getList();
            if (storeHouseBeans == null) {
                showToast("没有仓库，请创建仓库!");
            } else {
                mStoreHouseBeanList = storeHouseBeans;
                showPopup();
            }
        } else if (AllocatePresenter.TAG_ALLOCATE_ADD_MOVE_INFO.equals(httpResponse.getRequestTag())) {
            if (homeScan) {
                LiveEventBus.get(StorehouseHomeScanBackEvent.class).post(new StorehouseHomeScanBackEvent());
            } else {
                LiveEventBus.get(AllocateAddEvent.class).post(new AllocateAddEvent());
            }
            showToast("调拨成功");
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderBinding != null) {
            mHeaderBinding.unbind();
        }
    }
}
